package com.vincent.common.utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Vincent on 2014/10/17.
 */
public class ContextUtil {

    public static final String SESSION="session";
    public static final String REQUEST="request";
    public static final String RESPONSE="response";

    private static ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<Map<String, Object>>();

    public static void set(Object obj, String key) {
       Map<String,Object> dataMap = threadLocal.get();
        if (dataMap == null) {
            dataMap = new HashMap<String, Object>();
            threadLocal.set(dataMap);
        }
        dataMap.put(key, obj);
    }

    public static Map<String, Object> get() {
        return threadLocal.get();
    }

    public static HttpSession getSession(){
        Map<String, Object> map = threadLocal.get();
        if(map==null){
            return null;
        }
        Object o = map.get(SESSION);
        if(o==null||!(o instanceof HttpSession)){
            return null;
        }
        return (HttpSession) o;
    }
    public static HttpServletRequest getRequest(){
        Map<String, Object> map = threadLocal.get();
        if(map==null){
            return null;
        }
        Object o = map.get(REQUEST);
        if(o==null||!(o instanceof HttpServletRequest)){
            return null;
        }
        return (HttpServletRequest) o;
    }

    public static HttpServletResponse getResponse(){
        Map<String, Object> map = threadLocal.get();
        if(map==null){
            return null;
        }
        Object o = map.get(RESPONSE);
        if(o==null||!(o instanceof HttpServletResponse)){
            return null;
        }
        return (HttpServletResponse) o;
    }
}
